package com.tmsps.ne4weixin.api.pc;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tmsps.ne4weixin.bean.UserInfo;
import com.tmsps.ne4weixin.config.PcConfig;
import com.tmsps.ne4weixin.utils.WXHttpUtil;

import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.util.StrUtil;

/**
 *	@ClassName: LoginAPI
 *	@Description: https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
 *	@author: zhangwei(Mr.z).396033084@qq.com
 *	@date： 2022/09/15
 *	@Copyright: 行歌信息	
 */
public class LoginAPI extends PCBaseAPI {
	public LoginAPI(PcConfig config) {
		super(config);
	}
	
	/**
	 * 	@Description: PC端扫码登录
	 *	@author: zhangwei(Mr.z).396033084@qq.com
	 *	@date： 2022/09/15
	 */
	public String getScanUrl(String redirect_uri, String state) {
		state = StrUtil.isEmptyIfStr(state) ? "STATE" : state;
		String url = String.format(PC_SCAN_LOGIN, config.getAppid(), URLEncodeUtil.encode(redirect_uri), "snsapi_login", state);
		return url;
	}

	public String getAccessToken(String code) {
		String url = String.format(OAUTH2_GET_ACCESS_TOKEN, config.getAppid(), config.getSecret(), code);
		return WXHttpUtil.get(url);
	}
	
	public UserInfo getUserInfo(String accessToken, String openId) {
		String result = WXHttpUtil.get(String.format(GET_USERINFO, accessToken, openId));
		JSONObject userString = JSON.parseObject(result);
		return JSON.to(UserInfo.class, userString);
	}
}
